
#include "CudaThread.h"

using namespace ttg_internal::devices;

//------------------
//--- CudaThread ---
//------------------

void CudaThread::work()
{
	while (true)
	{
		ev1.wait();
		//Performing.
		action->invoke();
		//Unlocking.
		is_free_locker.enter();
		is_free = true;				//Note: flag was skipped by manager.
		is_free_locker.leave();
		ev2.rise();
	}
}

bool CudaThread::tryAcquire()
{
	bool is_succeeded = false;
	is_free_locker.enter();
	if (is_free)
	{
		is_succeeded = true;
		is_free = false;
	}
	is_free_locker.leave();
	return is_succeeded;
}

void CudaThread::perform(ttg::structures::InvokableObject *action)
{
	locker.enter();
#ifdef TTG_DEBUG
	if (this->action != NULL)
		throw ttg::Error(ttg::Error::FATAL, "CudaThread", "perform",
						 "The thread is still busy");
#endif
	this->action = action;
	ev1.rise();
	ev2.wait();
	SAFE_DELETE(this->action);
	locker.leave();
}
